<template>
    <div class="app-container">
        用户管理
        <!-- 顶部，查询表单 -->
        <div class="search-div">
            <el-form label-width="100px" size="small">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="关键字">
                            <el-input v-model="sysUserQueryVo.keyword" style="width: 80%;"
                                placeholder="用户名/姓名/手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="操作时间">
                            <el-date-picker v-model="createTimes" type="datetimerange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                                style="margin-right: 10px;width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="display: flex;">
                    <el-button type="primary" icon="el-icon-search" @click="fetchData()" size="small">搜 索</el-button>
                    <el-button icon="el-icon-refresh" size="small" @click="resetData()">重 置</el-button>
                </el-row>
            </el-form>
        </div>

        <!-- 添加，工具条 -->
        <!-- ### 按钮权限控制：$hasBP('bnt.sysRole.add')控制按钮是否显示 -->
        <div class="tools-div">
            <el-button type="success" icon="el-icon-plus" size="mini" @click="add()" :disabled="$hasBP('bnt.sysRole.add')  === false">添 加</el-button>
        </div>
        <!-- 在table组件上添加：“复选” 和 勾选触发事件 -->
        <el-dialog title="添加/修改" :visible.sync="dialogVisible" align="left" width="40%" style="color: #000;;">
            <el-form :model="sysUser" label-width="60px" size="small" style="padding-right: 40px;">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="sysUser.username" placeholder="请填入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="sysUser.password" type="password"></el-input>
                </el-form-item>
                <el-form-item v-if="!sysUser.id" label="姓名" prop="name">
                    <el-input v-model="sysUser.name" />
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="sysUser.phone" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
                <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 表格 -->
        <el-table v-loading="listLoading" :data="list" stripe border style="width: 100%; margin-top: 10px;">
            <el-table-column label="序号" width="70" align="center">
                <template slot-scope="scope">
                    {{ (page - 1) * limit + scope.$index + 1 }}
                </template>
            </el-table-column>

            <el-table-column label="用户名" prop="username" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" width="110" />
            <el-table-column prop="phone" label="手机" />
            <el-table-column label="状态" width="80">
                <!-- switch开关 -->
                <template slot-scope="scope">
                    <!-- 通过<template slot-scope="scope">，取该行的值 -->
                    <el-switch v-model="scope.row.status === 1" @change="switchStatus(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="scope">
                    <!-- 通过<template slot-scope="scope">，取该行的值 -->
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)">修改
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除
                    </el-button>
                    <el-button type="warning" icon="el-icon-baseball" size="small" @click="showAssignRole(scope.row)">
                        分配角色
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加分配角色表单 -->
        <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
            <el-form label-width="80px">
                <el-form-item label="用户名">
                    <el-input disabled :value="sysUser.username"></el-input>
                </el-form-item>
                <el-form-item label="角色列表">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange()">全选
                    </el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="userRoleIds" @change="handleCheckedCitiesChange()">
                        <el-checkbox v-for="role in allRoles" :label="role.id" :key="role.id">{{role.roleName}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button type="primary" @click="assignRole()" size="small">保存</el-button>
                <el-button @click="dialogRoleVisible = false" size="small">取消</el-button>
            </div>
        </el-dialog>

        <!-- 分页组件 -->
        <el-pagination @size-change="total" @current-change="fetchData" :current-page="page" :page-size="limit"
            :page-sizes="[3, 5, 8, 10]" style="padding: 30px; text-align: right;"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </div>
</template>

<script>
    //（1）引入，定义接口的js文件
    import api from '@/api/system/user'
    import roleApi from '@/api/system/role'

    //（2）定义初始值、生命周期函数、具体方法列表
    export default {
        data() {
            return {
                // 分页条件查询
                list: [],   // 角色列表
                total: 0,
                page: 1,    // 页码
                limit: 3,
                sysUserQueryVo: {},  // 查询条件
                // 搜索栏，操作时间
                createTimes: [],
                // 表格，数据是否正在加载
                listLoading: false,
                sysUser: {},  // 封装要添加的数据
                dialogVisible: false,   // 是否弹出“弹出层”
                // saveBtnDisabled: false
                // 用户分配角色
                dialogRoleVisible: false,
                allRoles: [], // 所有角色列表
                userRoleIds: [], // 用户的角色ID的列表
                isIndeterminate: false, // 是否是不确定的
                checkAll: false // 是否全选
            }
        },
        // 生命周期函数：内存准备完毕，页面尚未渲染
        created() {
            console.log('list created()......')
            this.fetchData();
        },
        // 生命周期函数：内存准备完毕，页面渲染成功
        mounted() {
            console.log('list mounted()......')
        },
        methods: {
            // ---加载banner列表数据---
            fetchData(pageNum = 1) {
                this.page = pageNum;
                // 补充，操作时间
                if (this.createTimes && this.createTimes.length == 2) {
                    this.sysUserQueryVo.createTimeBegin = this.createTimes[0];
                    this.sysUserQueryVo.createTimeEnd = this.createTimes[1];
                }
                // 调用，查询API
                api.userPageSel(this.page, this.limit, this.sysUserQueryVo).then(
                    response => {
                        console.log(response);
                        this.list = response.data.records;
                        this.total = response.data.total;
                        // 数据加载并绑定成功
                        this.listLoading = false;
                    }
                )
            },
            // 重置表单：（1）清空查询条件；（2）查询所有
            resetData() {
                // this.list = [];
                this.sysUserQueryVo = {};
                this.createTimes = [];
                this.fetchData();
            },

            add() {
                //（1）----先：清空表单----
                this.sysUser = {};
                //（2）弹出，弹出层
                this.dialogVisible = true;

            },
            saveOrUpdate() {
                // 判断：添加？修改？
                if (!this.sysUser.id) {
                    this.saveRole();
                } else {
                    this.updateRole();
                }
            },
            saveRole() {
                api.userSave(this.sysUser).then(
                    response => {
                        this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        this.dialogVisible = false;
                        this.fetchData();
                    }
                )
            },

            // 修改：（1）根据ID查询要修改的内容---“回显”；（2）修改表单内容，提交修改到数据库
            editUser(id) {
                // alert("显示啊....")
                this.dialogVisible = true;
                api.userGet(id).then(
                    response => {
                        this.sysUser = response.data;
                    }
                )
            },
            updateRole() {
                api.userUpdate(this.sysUser).then(
                    response => {
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                        this.dialogVisible = false;
                        this.fetchData();
                    }
                )
            },
            // 删除
            removeUserById(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 调用API，进行删除
                    api.userRemove(id).then(
                        response => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            //（3）刷新列表
                            this.fetchData();
                        }
                    )
                });
            },

            // 更改用户状态
            switchStatus(row) {
                // 取反，更改
                row.status = (row.status === 1 ? 0 : 1);
                // 调用API
                api.updateStatus(row.id, row.status).then(
                    response => {
                        this.$message.success(response.message || '操作成功');
                        // 刷新页面
                        this.fetchData()
                    }
                )
            },


            //（1）---显示：用户分配角色---
            showAssignRole(row) {
                this.sysUser = row; // 行赋值
                this.dialogRoleVisible = true;  // 显示弹出
                // 调用API
                roleApi.getRolesByUserId(row.id).then(
                    response => {
                        // console.log(response);
                        this.allRoles = response.data.allRoles;
                        this.userRoleIds = response.data.userRoleIds;
                        this.checkAll = (this.userRoleIds.length === this.allRoles.length);
                        this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length;
                    }
                )
            },
            // 全选勾选状态发生改变的监听
            handleCheckAllChange(value) {   // value：当前勾选状态true/false
                // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
                this.userRoleIds.length = value ? this.allRoles.map(item => item.id) : [];
                // 如果当前不是全选也不全不选时, 指定为false
                this.isIndeterminate = false;
            },
            // 角色列表选中项发生改变的监听
            handleCheckedCitiesChange(value) {
                const { userRoleIds, allRoles } = this;
                this.checkAll = (userRoleIds.length === allRoles.length && allRoles.length > 0);
                this.isIndeterminate = (userRoleIds.length > 0 && userRoleIds.length < allRoles.length);
            },
            //（2）---分配角色---
            assignRole() {
                let assginRoleVo = {
                    userId: this.sysUser.id,
                    roleIdList: this.userRoleIds
                };
                roleApi.assignRoles(assginRoleVo).then(
                    response => {
                        this.$message.success(response.message || '分配角色成功');
                        this.dialogRoleVisible = false;
                        this.fetchData(this.page);
                    }
                )
            },
        }
    }
</script>